package cs543.library.rmi;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.json.JSONArray;
import org.json.JSONObject;

public class RmiClientInterface {
	private final int PORT = 4242;
	private final int TIMEOUT = 1500; // in ms
	String address = null;

	public RmiClientInterface(String address) {
		this.address = address;
	}

	protected JSONArray invoque(String iface, String method, JSONArray args) {
		JSONObject rep = null;
		try {
			Socket clientSocket = new Socket();
			clientSocket.connect(new InetSocketAddress(address, PORT), TIMEOUT);
			DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

			JSONObject obj = new JSONObject();
			obj.put("interface", iface);
			obj.put("method", method);
			obj.put("args", args);
			output.writeBytes(obj.toString() + "\n");

			rep = new JSONObject(input.readLine());
		} catch (Exception e) {
			e.printStackTrace();
		}
		;

		try {
			if (!rep.getString("method").equals(method) || !rep.getString("interface").equals(iface))
				return null;
			try {
				JSONArray error = rep.getJSONArray("errors");
				return null;
			} catch (Exception e) {
				e.printStackTrace();
			}

			return rep.getJSONArray("values");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
